// pages/footprint/footprint.js
const api = require('../../utils/api')

Page({
  data: {
    sessions: [],
    loading: true,
    error: null,
    selectedSession: null,
    showReplayModal: false,
    totalStats: {
      totalDistance: 0,
      totalDuration: 0,
      totalPOIs: 0
    }
  },

  onLoad() {
    console.log('足迹页面初始化')
    this.loadSessionHistory()
  },

  onShow() {
    // Refresh data when page is shown
    this.loadSessionHistory()
  },

  /**
   * 加载散步历史记录
   */
  async loadSessionHistory() {
    this.setData({ loading: true, error: null })
    
    try {
      const result = await api.getSessionHistory()
      
      // Format sessions for display
      const formattedSessions = result.sessions.map(session => {
        return {
          ...session,
          formattedDate: this.formatDate(session.start_time),
          formattedTime: this.formatTime(session.start_time),
          formattedDistance: this.formatDistance(session.total_distance),
          formattedDuration: this.formatDuration(session.duration_minutes)
        }
      })
      
      // Calculate total stats
      const totalStats = this.calculateTotalStats(result.sessions)
      
      this.setData({
        sessions: formattedSessions,
        totalStats: totalStats,
        loading: false
      })
    } catch (error) {
      console.error('加载散步历史失败:', error)
      this.setData({
        error: '加载失败，请稍后重试',
        loading: false
      })
      
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  /**
   * 计算总统计信息
   */
  calculateTotalStats(sessions) {
    let totalDistance = 0
    let totalDuration = 0
    let totalPOIs = 0
    
    sessions.forEach(session => {
      totalDistance += session.total_distance || 0
      totalDuration += session.duration_minutes || 0
      totalPOIs += session.visited_poi_count || 0
    })
    
    return {
      totalDistance: this.formatDistance(totalDistance),
      totalDuration: this.formatDuration(totalDuration),
      totalPOIs: totalPOIs
    }
  },

  /**
   * 格式化日期
   */
  formatDate(isoString) {
    if (!isoString) return ''
    const date = new Date(isoString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  /**
   * 格式化时间
   */
  formatTime(isoString) {
    if (!isoString) return ''
    const date = new Date(isoString)
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${hours}:${minutes}`
  },

  /**
   * 格式化距离
   */
  formatDistance(meters) {
    if (!meters || meters === 0) return '0米'
    if (meters < 1000) {
      return `${Math.round(meters)}米`
    } else {
      return `${(meters / 1000).toFixed(2)}公里`
    }
  },

  /**
   * 格式化时长
   */
  formatDuration(minutes) {
    if (!minutes || minutes === 0) return '0分钟'
    if (minutes < 60) {
      return `${minutes}分钟`
    } else {
      const hours = Math.floor(minutes / 60)
      const mins = minutes % 60
      return mins > 0 ? `${hours}小时${mins}分钟` : `${hours}小时`
    }
  },

  /**
   * 查看路径回放
   */
  onViewReplay(e) {
    const sessionId = e.currentTarget.dataset.sessionId
    const session = this.data.sessions.find(s => s.id === sessionId)
    
    if (!session) {
      wx.showToast({
        title: '会话不存在',
        icon: 'none'
      })
      return
    }
    
    // Prepare map data for replay
    const mapData = this.prepareMapData(session)
    
    this.setData({
      selectedSession: session,
      showReplayModal: true,
      replayMarkers: mapData.markers,
      replayPolyline: mapData.polyline
    })
  },

  /**
   * 准备地图数据
   */
  prepareMapData(session) {
    const markers = []
    const polyline = []
    
    if (!session.route || !session.route.waypoints || session.route.waypoints.length === 0) {
      return { markers, polyline }
    }
    
    // Create markers for start and end points
    const waypoints = session.route.waypoints
    
    // Start marker
    if (waypoints.length > 0) {
      markers.push({
        id: 0,
        latitude: waypoints[0].latitude,
        longitude: waypoints[0].longitude,
        iconPath: '/images/footprint.png',
        width: 30,
        height: 30,
        title: '起点'
      })
    }
    
    // End marker
    if (waypoints.length > 1) {
      const lastPoint = waypoints[waypoints.length - 1]
      markers.push({
        id: 1,
        latitude: lastPoint.latitude,
        longitude: lastPoint.longitude,
        iconPath: '/images/footprint-active.png',
        width: 30,
        height: 30,
        title: '终点'
      })
    }
    
    // Create polyline for the route
    polyline.push({
      points: waypoints.map(wp => ({
        latitude: wp.latitude,
        longitude: wp.longitude
      })),
      color: '#667eea',
      width: 4,
      arrowLine: true
    })
    
    return { markers, polyline }
  },

  /**
   * 关闭回放模态框
   */
  onCloseReplayModal() {
    this.setData({
      showReplayModal: false,
      selectedSession: null
    })
  },

  /**
   * 查看会话详情
   */
  onViewDetail(e) {
    const sessionId = e.currentTarget.dataset.sessionId
    const session = this.data.sessions.find(s => s.id === sessionId)
    
    if (!session) {
      wx.showToast({
        title: '会话不存在',
        icon: 'none'
      })
      return
    }
    
    // Show detail modal with all session information
    const detailText = `
开始时间: ${session.formattedDate} ${session.formattedTime}
结束时间: ${this.formatTime(session.end_time)}
总距离: ${session.formattedDistance}
总时长: ${session.formattedDuration}
访问景点: ${session.visited_poi_count}个
    `.trim()
    
    wx.showModal({
      title: '散步详情',
      content: detailText,
      showCancel: false,
      confirmText: '确定'
    })
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadSessionHistory().then(() => {
      wx.stopPullDownRefresh()
    })
  }
})
